/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package pe.emp.solbrillante.sales.view;

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
import java.awt.event.MouseEvent;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.DefaultTableModel;
import pe.emp.solbrillante.sale.Main;
import pe.emp.solbrillante.sales.bean.PaqueteCompra;
import pe.emp.solbrillante.sales.bean.Producto;
import pe.emp.solbrillante.sales.bean.Proveedor;

/**
 *
 * @author TacbaranNew
 */
public class JProducto extends javax.swing.JDialog {

    /**
     * Creates new form JProducto
     */
    public JProducto(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
         //pintamos el fondo de la ventana
        ((JFondo)jventana).setImagen("fondo_subVentanal_II.jpg");
        
        //llenamos los arreglos
        ArrayList<Producto> productos = Main.myService.queryAllProductos();
        ArrayList<Proveedor> proveedores = Main.myService.queryAllProveedores();

        // El campo para todos los productos
       this.jComboBox1.addItem("TODOS");
        
          //recorremos desde 1 porque no queremos el nombre de la etiqueta
        for(int i=1; i<proveedores.size();i++ )
        {
            
//          this.jComboBox1.addItem(proveedores.get(i).getNombre());
//          combobox de objetos :  se sobreescribe el metodo toString() en proveedores
            this.jComboBox1.addItem(proveedores.get(i));
        
        }

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jventana = new JFondo();
        jLabel1 = new javax.swing.JLabel();
        jComboBox1 = new javax.swing.JComboBox();
        btnAgregar = new javax.swing.JButton();
        btnModificar = new javax.swing.JButton();
        btnEliminar = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTableListaProveedor = new javax.swing.JTable();
        jLabel2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setText("Filtro Proveedor");

        jComboBox1.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        jComboBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox1ActionPerformed(evt);
            }
        });

        btnAgregar.setText("Agregar");
        btnAgregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAgregarActionPerformed(evt);
            }
        });

        btnModificar.setText("Guardar Modificacion");
        btnModificar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnModificarActionPerformed(evt);
            }
        });

        btnEliminar.setText("Eliminar");
        btnEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarActionPerformed(evt);
            }
        });

        jTableListaProveedor.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane2.setViewportView(jTableListaProveedor);

        jLabel2.setText("Lista de Productos");

        javax.swing.GroupLayout jventanaLayout = new javax.swing.GroupLayout(jventana);
        jventana.setLayout(jventanaLayout);
        jventanaLayout.setHorizontalGroup(
            jventanaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jventanaLayout.createSequentialGroup()
                .addGroup(jventanaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 670, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jventanaLayout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(btnAgregar, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(32, 32, 32)
                        .addComponent(btnModificar, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(btnEliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jventanaLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 176, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(11, 11, 11)))
                .addContainerGap())
        );
        jventanaLayout.setVerticalGroup(
            jventanaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jventanaLayout.createSequentialGroup()
                .addGap(58, 58, 58)
                .addGroup(jventanaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel2)
                    .addGroup(jventanaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel1)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 240, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jventanaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnAgregar)
                    .addComponent(btnModificar)
                    .addComponent(btnEliminar))
                .addContainerGap(58, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jventana, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jventana, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed
        // TODO add your handling code here:
        
//        String proveedorDeproducto = this.jComboBox1.getSelectedItem().toString();
//        //this.jLabel_proveedor.setText(proveedor_sel);
//         MostarProductosDeProveedor(proveedorDeproducto);
        
        
        //este metodo actualiza la tabla por que  solo dios sabe por que !!! XD
           refreshProductTable();
        
    }//GEN-LAST:event_jComboBox1ActionPerformed

    public void refreshProductTable(){
        if( ! this.jComboBox1.getSelectedItem().equals("TODOS"))
        {
        Proveedor proveedor = (Proveedor)this.jComboBox1.getSelectedItem();
        MostarProductos(proveedor.getId());
        }
        else{
                MostarProductos(-1);
        }
    }
    
    
    private void btnModificarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnModificarActionPerformed
        // TODO add your handling code here:
        //selecionas las fila de la tabla
        int fil = this.jTableListaProveedor.getSelectedRow();
        //int idProduct =  );

        
                Object[] fila = new Object[8];
                                  
                                  fila[0] = Integer.parseInt( this.jTableListaProveedor.getValueAt(fil, 0).toString() ) ;
                                  fila[1] = this.jTableListaProveedor.getValueAt(fil, 1).toString();
                                  fila[2] = this.jTableListaProveedor.getValueAt(fil, 2).toString();
                                  fila[3] = this.jTableListaProveedor.getValueAt(fil, 3).toString();
                                  fila[4] = this.jTableListaProveedor.getValueAt(fil, 4).toString();
                                  fila[5] = this.jTableListaProveedor.getValueAt(fil, 5).toString();
                                  fila[6] = this.jTableListaProveedor.getValueAt(fil, 6).toString();
                                  fila[7] = Integer.parseInt( this.jTableListaProveedor.getValueAt(fil, 7).toString() ) ;
        Main.myService.updateProduct( fila);
        
    }//GEN-LAST:event_btnModificarActionPerformed

    private void btnAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAgregarActionPerformed
        // TODO add your handling code here:
        
                           JProductoNuevo jnewproveedor;
                   jnewproveedor = new JProductoNuevo(new VentanaPrincipalLogin(), true);
                   jnewproveedor.setVisible(true);
        
        
    }//GEN-LAST:event_btnAgregarActionPerformed

    private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarActionPerformed
        // TODO add your handling code here:

        //selecionas las fila de la tabla
        int fil = this.jTableListaProveedor.getSelectedRow();
        int idProduct = Integer.parseInt( this.jTableListaProveedor.getValueAt(fil, 0).toString() );

           Main.myService.queryDeleteProducto(   idProduct    );
        
           //refresaca la tabla
          refreshProductTable();
    }//GEN-LAST:event_btnEliminarActionPerformed
   
    private void MostarProductos( int id ){
        
        //incio de la creacion de la tabla
        DefaultTableModel modelo = new DefaultTableModel();                
               
            
            modelo = new DefaultTableModel(){
            boolean[] canEdit = new boolean [] { false, true, true, true,true, true, true, true };

            @Override
                         public boolean isCellEditable(int rowIndex, int columnIndex) {
                             return canEdit [columnIndex];
                         }

            };
            
            this.jTableListaProveedor.setModel(modelo);  
        
       //fin de la creacion

            
           ArrayList<Object>  tabla =  Main.myService.queryAllProductoDetalle(id);

    
            modelo.addColumn("Codigo");
            modelo.addColumn("Producto");
            modelo.addColumn("Proveedor");
            modelo.addColumn("Tipo");
            modelo.addColumn("Unidad por paquete");
            modelo.addColumn("Stock Min");
            modelo.addColumn("Stock Min");
            modelo.addColumn("Cantidad Actual");

            
           System.out.println("size : " + tabla.size());
            for (int i = 0; i < tabla.size(); i++) {                           
                modelo.addRow(  (Object[])tabla.get(i) );  
               
                
            }         
            
         
    }
       
       
    private void MostarProductosDeProveedor(Proveedor proveedorDeproducto) {
                       //Declaramos las clases necesarias para la conexion     
            
        DefaultTableModel modelo = new DefaultTableModel();                
               
            
            modelo = new DefaultTableModel(){
            boolean[] canEdit = new boolean [] { false, true,true, true, true, true };

            @Override
                         public boolean isCellEditable(int rowIndex, int columnIndex) {
                             return canEdit [columnIndex];
                         }

            };
            
            this.jTableListaProveedor.setModel(modelo); 
            
            System.out.println(proveedorDeproducto.getId());   
            //ArrayList<Paquete> paquetesxproveedor = Main.myService.queryPaquetesxProveedor(proveedorDeproducto.getId());
            ArrayList<PaqueteCompra> paquetesxproveedor = Main.myService.queryPaquetesxProveedorS(proveedorDeproducto.getId());
                 
    
            modelo.addColumn("Codigo");
            modelo.addColumn("Proveedor");
            modelo.addColumn("Producto");
            modelo.addColumn("Unidades");
            modelo.addColumn("PrecioxPaquete");
            modelo.addColumn("Cantidad");
            
           System.out.println("size : " + paquetesxproveedor.size());
            for (int i = 0; i < paquetesxproveedor.size(); i++) {                           
                //Extraemos los datos del ResultSet nombre=nombre de la columna              
                Object[] fila = new Object[6];                
                
                fila[0]=paquetesxproveedor.get(i).getCodigo();
                fila[1]=paquetesxproveedor.get(i).getNom_prov();
                fila[2]=paquetesxproveedor.get(i).getNom_prd();
                fila[3]=paquetesxproveedor.get(i).getUnixpaquete();
                fila[4]=paquetesxproveedor.get(i).getPrecioxpaquete();
                fila[5]=paquetesxproveedor.get(i).getCantidad();
                
                //System.out.println(paquetesxproveedor.get(i).getId()+"..."+paquetesxproveedor.get(i).getCantidad_actual());
                modelo.addRow(fila);     
              
            }   
 
    }
    
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(JProducto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(JProducto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(JProducto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(JProducto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                JProducto dialog = new JProducto(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAgregar;
    private javax.swing.JButton btnEliminar;
    private javax.swing.JButton btnModificar;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTableListaProveedor;
    private javax.swing.JPanel jventana;
    // End of variables declaration//GEN-END:variables




}
